<?php

namespace app\admin\controller;

use app\common\model\OrderGoodsclasses as OrderGoodsclassesModel;
use app\common\model\Mall;
use app\common\model\Student;
use app\service\UserService;

class Ordergoodsclasses extends Base
{

    public function __construct()
    {
        parent::__construct();

    }

    /*
     列表
     */
    public function list()
    {
        $where = array();
        $input = input();
        $page = max(input('page'), 1);
        $size = 20;
        $whereArr = $this->buildQuery();
        if ($input['excel']) {
            //导出excel
            $orderList = OrderGoodsclassesModel::getAll($whereArr, 'pay_time desc,create_time desc');
            if (!$orderList) {
                return returnJson(1, '无数据');
            }
            if (!($input['create_time_start'] && $input['create_time_end']) && !($input['pay_time_start'] && $input['pay_time_end'])) {
                return returnJson(1, '必须选择一个时间区间');
            }
            if ($input['create_time_start'] && $input['create_time_end'] && (strtotime($input['create_time_end']) - strtotime($input['create_time_start'])) > 31 * 24 * 3600) {
                return returnJson(1, '订单创建时间区间不能超过31天');
            }
            if ($input['pay_time_start'] && $input['pay_time_end'] && (strtotime($input['pay_time_end']) - strtotime($input['pay_time_start'])) > 31 * 24 * 3600) {
                return returnJson(1, '订单支付时间区间不能超过31天');
            }
            $file = $this->exportExcel($orderList);
            return returnJson(0, '', $file);
        }
        $orderList = OrderGoodsclassesModel::getPage($whereArr, $page, $size, 'pay_time desc,create_time desc');
        $total = OrderGoodsclassesModel::getCount($whereArr);
        if (!$orderList) {
            return returnJson(0, '', [
                'list' => [],
                'size' => $size,
                'total' => 0
            ]);
        }
        foreach ($orderList as $k => $v) {
            $orderList[$k]['goods_list'] = json_decode($v['goods_list'], true);
                $orderList[$k]['goods_list']['picture'] = $orderList[$k]['goods_list']['picture'] ? tomedia($orderList[$k]['goods_list']['picture']) : '';
            $orderList[$k]['userInfo'] = UserService::S()->findUser(['id' => $v['uid']], ['nickname', 'id']);

            $orderList[$k]['status_text'] = $this->getStatusText($v['checked']);
            $orderList[$k]['mallInfo'] = Mall::getOneById($v['mall_id'], 'id,name,money');
            $orderList[$k]['student'] = Student::getValue(['id' => $v['sid']], 'name');
            $orderList[$k]['pay_time'] = date('Y-m-d H:i:s',$v['pay_time']);
        }
        return returnJson(0, '', [
            'list' => $orderList,
            'size' => $size,
            'total' => $total
        ]);
    }



    protected function exportExcel($list)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $arrData = [
            ['订单ID', '订单号', '用户ID', '用户昵称', '状态', '总金额', '订单信息', '创建时间', '支付时间']
        ];
        foreach ($list as $k => $v) {
            $v['userInfo'] = UserService::S()->findUser(['id' => $v['uid']], ['nickname', 'id']);
            $goodsList = json_decode($v['goods_list'], true);
            $status_text = $this->getStatusText($v['checked']);
            $goodsString = '';
            foreach ($goodsList as $goods) {
                $goodsString .= "{$goods['name']}\n";
            }
            $arrData[] = [
                $v['id'], $v['order_sn'], $v['uid'], $v['userInfo']['nickname'], $status_text, $v['all_money'],
                $goodsString,
                $v['create_time'], $v['pay_time']
            ];
        }
        $sheet->fromArray($arrData, NULL);
        $writer = new Xlsx($spreadsheet);
        $name = '订单信息-' . date('Y-m-d') . '-' . time() . ".xlsx";
        $path = ROOT_PATH . "public" . DS . "cache" . DS . $name;
        $writer->save($path);
        return request()->domain() . "/cache/" . $name;
    }

    protected function buildQuery()
    {
        $input = input();
        $where = [];
        if ($input['id']) {
            $where['id'] = ['eq', $input['id']];
        }
        if ($input['order_sn']) {
            $where['order_sn'] = ['eq', $input['order_sn']];
        }
        if ($input['uid']) {
            $where['uid'] = ['eq', $input['uid']];
        }
        if (isset($input['checked'])) {
            if ($input['checked'] != 'all') {
                $where['checked'] = ['eq', $input['checked']];
            }
        }
        if ($input['create_time_start']) {
            $where['create_time'] = ['>=', strtotime($input['create_time_start'])];
        }
        if ($input['create_time_end']) {
            $where['create_time'] = ['<=', strtotime($input['create_time_end'])];
        }
        if ($input['pay_time_start']) {
            $where['pay_time'] = ['>=', strtotime($input['pay_time_start'])];
        }
        if ($input['pay_time_end']) {
            $where['pay_time'] = ['<=', strtotime($input['pay_time_end'])];
        }
        return $where;
    }

    protected function getStatusText($status)
    {
        switch ($status) {
            case 0:
                $status_text = '待付款';
                break;
            case 1:
                $status_text = '已付款';
                break;
        }
        return $status_text;
    }




    /* 退款 */
    public function refund()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, '订单不存在');
        }
        $res = OrderService::S()->refundOrder($input['id']);
        if ($res === true) {
            return returnJson(0, '退款成功');
        } else {
            return returnJson(1, $res);
        }
    }


}
